<template>
  <el-dialog
    v-model="showDialog"
    :title="title"
    :append-to-body="true"
    :width="width"
    @closed="closeDialog"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <super-form
      :formAndTable="false"
      ref="classificationDialogRef"
      v-bind="formOption"
      :modelValue="formData"
      :rules="formRules"
    >
      <template v-if="[2, 3].includes(typeClass)" #custom>
        <el-select
          v-model="formData.typeOrUnitId"
          clearable
          filterable
          :placeholder="typeClass === 2 ? '请选择物料分类' : '请选择单位名称'"
        >
          <el-option v-for="item in materialTypeOrUnitList" :key="item.id" :label="item.name" :value="item.id">
            <template #default>
              <div class="flex justify-between">
                <div>{{ item.name }}</div>
                <div class="flex" v-if="item.buildFrom !== 1">
                  <div class="text-[#f56c6c] mr-2" @click.stop="handleOperate('删除', item)">删除</div>
                  <div class="text-[#409eff]" @click.stop="handleOperate('编辑', item)">编辑</div>
                </div>
              </div>
            </template>
          </el-option>
          <template #header>
            <el-input
              v-model.trim="formData.materialTypeOrUnitName"
              :maxlength="12"
              :placeholder="typeClass === 2 ? '请输入分类名称' : '请选择单位名称'"
            />
            <div class="pt-2">
              <el-button type="primary" size="small" @click="onConfirm('add')"> 确定 </el-button>
              <el-button size="small" @click="onConfirm('')">取消</el-button>
            </div>
          </template>
        </el-select>
      </template>
    </super-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog(true)"> 取 消 </el-button>
        <el-button type="primary" :loading="loading" @click.stop="handleSubmit" @keyup.enter="keyDown">
          确 定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, useTemplateRef } from "vue";
import SuperForm from "@/components/SuperForm/index.vue";
import { FormOption } from "@/components/SuperForm/formType";
import { type FormRules } from "element-plus";
import { FormClassification } from "./formConfig";
import { useConfirm } from "@/hooks/useConfirm";
import { ElInput } from "element-plus";
import {
  getMaterialType,
  addOrUpdateMaterialType,
  delMaterialType,
  getMaterialUnit,
  addOrUpdateMaterialUnite,
  delMaterialUnit,
  updateMaterial,
} from "@/api/materialFile";
interface Props {
  width?: number; // 宽度
  title?: string; // 标题
}
const { width = 800, title } = defineProps<Props>();
const emits = defineEmits<{
  handleSubmit: [_row: any];
  handleClose: any;
}>();
// 弹窗
const showDialog = ref<boolean>(false);
const loading = ref<boolean>(false);
// 表单ref实例
const classificationDialogRef = useTemplateRef<any>("classificationDialogRef");
// 表单
const formData = ref<any>({});
const formOption = ref<FormOption>({formItems: []});
const formRules = ref<FormRules>({});
// 打开
const typeClass = ref<number>(0);
const openDialog = (data: any = {}, _type: number): void => {
  typeClass.value = _type;
  const formClassification = new FormClassification();
  formRules.value = formClassification.formRules;
  formOption.value = formClassification.formOption;
  formOption.value["formItems"].forEach((item: any) => {
    if (item.classType) {
      item.isHidden = item.classType === _type ? false : true;
      if (item.isHidden) {
        formData.value[item.field] = null;
        formData.value[item.prop] = null;
        item.slotName = "";
      }
    }
  });
  Object.assign(formData.value, formClassification.formData, { ...data });
  if ([2, 3].includes(_type)) {
    _type === 2
      ? (formData.value.typeOrUnitId = data?.materialTypeId)
      : (formData.value.typeOrUnitId = data?.materialUnitId);
    getMaterialTypeOrUnit();
  }
  showDialog.value = true;
  loading.value = false;
  nextTick(() => {
    window.addEventListener("keydown", keyDown);
  });
};
// 关闭
const closeDialog = (bool: boolean = false): void => {
  classificationDialogRef.value?.ruleFormRef?.resetFields();
  showDialog.value = false;
  loading.value = false;
  formData.value = {};
  emits("handleClose", bool);
  window.removeEventListener("keydown", keyDown, false);
};
// 物料分类, 单位
const handleOperate = async (_type: string, _row: any) => {
  if (_type === "删除") {
    const { showConfirm } = useConfirm(
      "警告",
      `是否删除选择的${typeClass.value === 2 ? "分类名称" : "单位名称"}，删除后不可以恢复？`
    );
    const confirmed = await showConfirm();
    if (confirmed) {
      const params: any = {};
      typeClass.value === 2 ? (params.materialTypeId = _row.id) : (params.materialUnitId = _row.id);
      const fnDel = typeClass.value === 2 ? delMaterialType : delMaterialUnit;
      fnDel(params).then((res: any) => {
        if (res) {
          ElMessage.success("删除成功");
          params.materialTypeId === _row.id || params.materialUnitId === _row.id
            ? (formData.value.typeOrUnitId = "")
            : null;
          getMaterialTypeOrUnit();
        }
      });
    }
  } else {
    const typeOrUnitName = ref<string>("");
    typeOrUnitName.value = _row?.name || "";
    ElMessageBox({
      title: `${typeClass.value === 2 ? "编辑分类" : "编辑单位"}`,
      showCancelButton: true,
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      closeOnClickModal: false,
      beforeClose: (action, instance, done) => {
        if (action === "confirm") {
          if (!typeOrUnitName.value)
            return ElMessage.error(`${typeClass.value === 2 ? "请输入分类名称" : "请输入单位名称"}`);
          const params = {
            name: typeOrUnitName.value,
            id: _row.id,
          };
          const fnTypeOrUnit = typeClass.value === 2 ? addOrUpdateMaterialType : addOrUpdateMaterialUnite;
          fnTypeOrUnit(params)
            .then((res: any) => {
              if (res) {
                instance.confirmButtonLoading = true;
                instance.confirmButtonDisabled = false;
                ElMessage.success("编辑成功");
                typeOrUnitName.value = "";
                getMaterialTypeOrUnit();
                // 这里调用接口
                done();
              }
            })
            .catch(() => {
              typeOrUnitName.value = "";
              done();
            });
        } else {
          typeOrUnitName.value = "";
          done();
        }
      },
      message: () =>
        h(ElInput, {
          modelValue: typeOrUnitName.value,
          "onUpdate:modelValue": (val: any) => {
            typeOrUnitName.value = val;
          },
        }),
    });
  }
};
// 获取物料分类Or单位
const materialTypeOrUnitList = ref<any[]>([]);
const getMaterialTypeOrUnit = () => {
  const params = {
    page: 1,
    limit: 1000,
  };
  const fn = typeClass.value === 2 ? getMaterialType : getMaterialUnit;
  const dataRoot = typeClass.value === 2 ? "materialTypes" : "materialUnits";
  fn(params).then((res: any) => {
    if (res) {
      const obj: any = res[dataRoot];
      const { items } = obj;
      materialTypeOrUnitList.value = items;
    }
  });
};
// 新增物料分类, 单位
const onConfirm = (_type: string) => {
  if (_type) {
    if (!formData.value.materialTypeOrUnitName) return ElMessage.error("请输入分类名称");
    if (formData.value.materialTypeOrUnitName) {
      const params = {
        name: formData.value?.materialTypeOrUnitName,
      };
      const fn = typeClass.value === 2 ? addOrUpdateMaterialType : addOrUpdateMaterialUnite;
      fn(params).then((res: any) => {
        if (res) {
          ElMessage.success("新增成功");
          getMaterialTypeOrUnit();
        }
      });
    }
    formData.value.materialTypeOrUnitName = "";
  } else {
    formData.value.materialTypeOrUnitName = "";
  }
};
// 物料档案表单提交
const handleSubmit = (): void => {
  classificationDialogRef.value.ruleFormRef.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const params: any = {
        materialId: formData.value.id,
        materialTypeId: formData.value.materialTypeId,
        materialUnitId: formData.value.materialUnitId,
        name: formData.value.name,
        code: formData.value.code,
      };
      typeClass.value === 2
        ? (params.materialTypeId = formData.value?.typeOrUnitId)
        : typeClass.value === 3
          ? (params.materialUnitId = formData.value?.typeOrUnitId)
          : (params.code = formData.value?.code);
      updateMaterial(params)
        .then((res: any) => {
          if (res) {
            ElMessage.success("修改成功");
            closeDialog(true);
          }
        })
        .catch(() => {
          loading.value = false;
        });
      // 接口
    } else {
      loading.value = false;
    }
  });
};
// 键盘事件
const keyDown = (e: any) => {
  if (e.keyCode === 13) {
    handleSubmit();
  }
};

defineExpose({
  closeDialog,
  openDialog,
});
</script>
